<template>
  <a-row style="width: 752px; min-height: 520px">
    <!-- 左侧分类 -->
    <a-col :span="7">
      <div v-if="init" class="float-left text-center mt-30">
        <a-spin />
      </div>
      <div class="float-left" v-show="!init">
        <TreeCategory
          :selected="[]"
          type="no-cate"
          :text="label"
          @update="setCategoryIds"
        />
      </div>
    </a-col>

    <!-- 右侧课件表格 -->
    <a-col :span="17">
      <!-- 顶部搜索 -->
      <a-row style="margin-bottom: 24px; padding-left: 10px">
        <div class="float-left j-b-flex">
          <div class="d-flex"></div>
          <div class="d-flex">
            <div class="d-flex mr-24">
              <a-typography-text>名称：</a-typography-text>
              <a-input
                v-model:value="title"
                allow-clear
                style="width: 160px"
                placeholder="请输入名称关键字"
                @change="handleTitleChange"
              />
            </div>
            <div class="d-flex">
              <a-button class="mr-16" @click="resetVideoList">重 置</a-button>
              <a-button type="primary" @click="handleQuery">
                查 询
              </a-button>
            </div>
          </div>
        </div>
      </a-row>

      <!-- 表格内容 -->
      <div v-if="init" class="float-left text-center mt-30">
        <a-spin />
      </div>

      <div class="video-list" v-show="!init">
        <a-col v-if="videoList.length === 0 && !init" :span="24" style="margin-top: 150px">
          <a-empty description="暂无课件" />
        </a-col>

        <div v-else-if="videoList.length > 0" class="list-select-column-box c-flex">
          <a-table
            row-key="id"
            :row-selection="rowSelection"
            :columns="columns"
            :data-source="videoList"
            :loading="loading"
            :pagination="paginationProps"
          />
        </div>
      </div>
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
import { ref, reactive, watch, h, computed, onMounted } from "vue";
import type { TableProps } from "ant-design-vue";
import { resource } from "../../api";
import TreeCategory from "./tree-category.vue";

interface VideoItem {
  id: number;
  name: string;
  created_at: string;
  type: string;
  url: string;
  path: string;
  size: number;
  extension: string;
  admin_id: number;
}

interface PropsInterface {
  defaultCheckedList: any[];
  label: string;
  open: boolean;
  onSelected: (arr: any[], videos: any[]) => void;
}

const props = defineProps<PropsInterface>();

const init = ref(true);
const category_ids = ref<any[]>([]);
const loading = ref(false);
const videoList = ref<VideoItem[]>([]);
const existingTypes = ref<any[]>([]);
const refresh = ref(false);
const page = ref(1);
const size = ref(10);
const total = ref(0);
const selectedRowKeys = ref<any[]>([]);
const title = ref("");
const requestTimer = ref<NodeJS.Timeout>();

// 防抖的课件列表获取函数
const getVideoList = () => {
  if (!props.open) {
    return;
  }
  
  // 清除之前的定时器
  if (requestTimer.value) {
    clearTimeout(requestTimer.value);
  }
  
  requestTimer.value = setTimeout(() => {
    init.value = true;
    loading.value = true;
    const categoryIds = category_ids.value.join(",");
    
    resource
      .resourceList(
        page.value,
        size.value,
        "",
        "",
        title.value,
        "WORD,EXCEL,PPT,PDF,TXT,RAR,ZIP",
        categoryIds
      )
      .then((res: any) => {
        if (res && res.data) {
          total.value = res.data.result?.total || 0;
          existingTypes.value = res.data.existing_types || [];
          videoList.value = res.data.result?.data || [];
        } else {
          console.warn('课件API响应数据格式异常');
          videoList.value = [];
          total.value = 0;
          existingTypes.value = [];
        }
      })
      .catch((err: any) => {
        console.error("课件API错误:", err);
        videoList.value = [];
        total.value = 0;
        existingTypes.value = [];
      })
      .finally(() => {
        loading.value = false;
        init.value = false;
      });
  }, 300);
};

// 组件挂载时加载数据
onMounted(() => {
  if (props.open) {
    getVideoList();
  }
});

// 监听props.open变化
watch(() => props.open, (newVal) => {
  if (newVal) {
    getVideoList();
  } else {
    // 关闭时清空数据
    videoList.value = [];
    existingTypes.value = [];
    total.value = 0;
  }
}, { immediate: true });

// 监听其他参数变化
watch(() => ({
  category_ids: [...category_ids.value],
  page: page.value,
  size: size.value,
  refresh: refresh.value
}), () => {
  if (props.open) {
    getVideoList();
  }
});

// 监听defaultCheckedList变化
watch(() => props.defaultCheckedList, (val) => {
  selectedRowKeys.value = [...val];
}, { immediate: true });

// 重置
const resetVideoList = () => {
  page.value = 1;
  title.value = "";
  category_ids.value = [];
  getVideoList();
};

// 查询
const handleQuery = () => {
  page.value = 1;
  getVideoList();
};

// 标题变化
const handleTitleChange = (e: Event) => {
  title.value = (e.target as HTMLInputElement).value;
};

// 分页
const paginationProps = reactive({
  current: page,
  pageSize: size,
  total: total,
  showSizeChanger: true,
  onChange: (p: number, pageSize: number) => handlePageChange(p, pageSize),
});

const handlePageChange = (p: number, pageSize: number) => {
  page.value = p;
  size.value = pageSize;
};

// 表格列
const columns: TableProps["columns"] = [
  {
    title: "课件",
    key: "name",
    customRender: ({ record }: any) => {
      return h(
        "div",
        { class: "d-flex" },
        [
          h("i", {
            class: "iconfont icon-icon-file",
            style: { fontSize: "14px", color: "rgba(0,0,0,0.3)" },
          }),
          h("div", { class: "video-title ml-8" }, record.name),
        ]
      );
    },
  },
  {
    title: "类型",
    key: "type",
    dataIndex: "type",
    customRender: ({ text }: any) => {
      const typeMap: Record<string, string> = {
        'WORD': 'Word',
        'EXCEL': 'Excel',
        'PPT': 'PPT',
        'PDF': 'PDF',
        'TXT': 'TXT',
        'RAR': 'RAR',
        'ZIP': 'ZIP'
      };
      return typeMap[text] || text;
    },
  },
];

// 修复选中逻辑
const rowSelection = computed<TableProps["rowSelection"]>(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: any[], rows: any[]) => {
    // 修复：包含所有选中行的数据
    const arrVideos: any[] = rows.map((row: any) => ({
      name: row.name,
      type: row.type,
      rid: row.id,
    }));
    
    props.onSelected(keys, arrVideos);
    selectedRowKeys.value = keys;
  },
  getCheckboxProps: (record: any) => ({
    disabled: props.defaultCheckedList.includes(record.id),
  }),
}));

// 分类树回调
const setCategoryIds = (keys: any) => {
  category_ids.value = keys;
  page.value = 1;
  getVideoList();
};
</script>

<style scoped>
</style>